<template>
  <el-container>
    <el-header class="app-header">
      <el-row>
        <el-col :span="1" class="app-logo-wrapper" style="width: 210px;">
          <span style="background-image: url('static/logo.png');background-size:100px 33px;width: 100px;height:33px;"></span>&nbsp;<span class="app-logo-text"></span>
        </el-col>
        <el-col :span="18">
          <div class="app-logo-text" style="margin: 5px 20px 0 20px">{{ currentTime }}</div>
          <el-menu :default-active="defaultNav" class="app-nav" mode="horizontal" @select="chooseNav">
            <el-menu-item v-for="(e, i) in navs" :index="`${e.moduleId}`" :key="`${e.moduleId}`">
              {{e.moduleName}}
            </el-menu-item>

            <el-submenu index="more" :class="`${moreVisable} more`" >
              <template slot="title">更多</template>
              <el-menu-item v-for="(e, i) in navsMore" :index="`${e.moduleId}`" :key="`${e.moduleId}`">
                {{e.moduleName}}
              </el-menu-item>
            </el-submenu>
          </el-menu>
        </el-col>
        <div class="app-user-wrapper">
          <p class="context">
            <span class="env">{{currEnv}}</span>
            <el-dropdown trigger="click" @command="handleUserCommand">
              <span class="el-dropdown-link">
                <span class="user"> {{this.currUserName}} &nbsp;<i class="el-icon-caret-bottom"></i></span>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="employeeDialogVisible">个人信息</el-dropdown-item>
                <el-dropdown-item command="dialogFormVisible">修改密码</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </p>
        </div>
      </el-row>
    </el-header>

    <el-container class="app-wrapper">
      <el-aside class="app-tree" :style="{ width: treeWidth }">
        <el-tree v-show="showMenu" :data="navMenus.data"
                 :highlight-current="true"
                 :filter-node-method="filterMenu"
                 node-key="id"
                 :auto-expand-parent="true"
                 :default-expanded-keys="expendNode"
                 ref="menuTree" :props="MenuProps" @node-click="choosePage"></el-tree>
      </el-aside>
      <div class="menu-ctrl" :class="{'expand': !showMenu}"><span @click="toggleMenu"></span></div>
      <el-main class="app-main" :style="showMenu ? 'width: calc(100% - 200px);left: 200px;':'width: 100%;left: 0;'">
        <div class="app-main-wrapper">
          <el-tabs v-if="pages && pages.length > 0" v-model="defaultPage" @tab-click="chooseTab" type="card"
                   editable @edit="closeAll"
                   @tab-remove="close">
            <el-tab-pane
              :key="item.name"
              v-for="(item, index) in pages"
              :label="item.title"
              :name="item.name"
              :closable=item.closable
            >
              <welcome class="app-iframe" v-if="item.name === '0'"></welcome><iframe :id="'iframe' + item.name" :ref="'iframe' + index" v-else class="app-iframe" :src="item.path.indexOf('?') > -1 ?  item.path+ '&iframeType=iframePage' : item.path+ '?iframeType=iframePage'"></iframe>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules"
        ref="passwordForm"
        :model="passwdFormData"
        label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input type="password" name="oldPassword" v-model="passwdFormData.oldPassword"></el-input>
        </el-form-item>
        <el-form-item  label="新密码" prop="newPassword">
          <el-input type="password" name="newPassword" v-model="passwdFormData.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="重复新密码" prop="reNewPassword">
          <el-input type="password" name="reNewPassword" v-model="passwdFormData.reNewPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPasswdUpdate">取 消</el-button>
        <el-button type="primary" @click="updatePasswd">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="基本信息查看" :visible.sync="employeeDialogVisible">
      <el-form
        ref="employeeInfo"
        label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="员工编号" prop="empNo">
              <el-input type="input" name="empNo" v-model="employeeInfo.empNo" readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="员工姓名" prop="name">
              <el-input type="input" name="name" v-model="employeeInfo.name"  readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item  label="性别" prop="sex">
              <el-input type="input" name="name" v-model="employeeInfo.sex"  readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  label="员工手机" prop="mobile">
              <el-input type="input" name="name" v-model="employeeInfo.mobile"  readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item  label="员工邮箱" prop="email">
              <el-input type="input" name="email" v-model="employeeInfo.email"  readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item  label="是否离职" prop="email">
              <el-input type="input" name="email" v-model="employeeInfo.dimission"  readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </el-container>
</template>

<script>
  import './index.scss'
  import welcome from '@/view/welcome'
  import { mapGetters, mapActions } from 'vuex'
  import { recursion, cookies, getCurrEnvContext, passwordUtils } from '@/utils'
  import { indexApi } from '@/service/mock-api'
  // eslint-disable-next-line standard/object-curly-even-spacing
  import { indexApi as remoteApi} from '@/service/api'
  import {local} from '@/service/mock-data'
  /**
   * receiveMsg 接收 iframe 推送的 Msg
   *
   * @param  {Object}   event: 接收的对象
   */
  const receiveMsg = function (event) {
    const { data } = event
    switch (data.type) {
      case 'NO_LOGIN': // 未登录跳转至登录页
        location.assign('/#/login')
        break
      case 'NO_PERMISSION': // 未登录跳转至登录页
        this.$message({
          message: '该操作没有权限',
          type: 'warning'
        })
        break
      case 'REFRESH_MENU': // 刷新nav与树
        this.getNavs()
        break
      case 'EMIT':
        this.broadcastToIframe(data.value)
        break
      default:
    }
  }
  let handler = null
  export default {
    components: {
      'welcome': welcome
    },
    data () {
      var validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入新密码!'))
          return
        }
        let tip = passwordUtils.checkPassword(value)
        if (tip) {
          callback(new Error(tip))
          return
        }
        callback()
      }
      var validatePass2 = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请重复新密码'))
        }
        if (value !== this.passwdFormData.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        employeeDialogVisible: false,
        passwdFormData: {},
        employeeInfo: {},
        dialogFormVisible: false,
        currUserName: '',
        currEnv: '',
        defaultPage: '0',
        pages: [],
        navs: [], // 导航
        navsMore: [], // 导航更多
        moreVisable: 'hide',
        navMenus: [], // 左侧菜单
        defaultNav: '', // 默认导航选中
        expendNode: [],
        showMenu: true,
        MenuProps: {
          label: 'name',
          children: 'children'
        },
        messageBox: {
          num: '',
          timer: null,
          timer2: null
        },
        // 表单校验规则
        rules: {
          oldPassword: [
            {placeholder: '请输入旧密码', required: true, message: '请输入旧密码', trigger: 'change'}
          ],
          newPassword: [
            {validator: validatePass, trigger: 'change'},
            {placeholder: '请输入新密码', required: true, message: '请输入旧密码', trigger: 'change'}
          ],
          reNewPassword: [
            {validator: validatePass2, trigger: 'change'},
            {placeholder: '请重复新密码', required: true, message: '请输入旧密码', trigger: 'change'}
          ]
        }
      }
    },
    // store,
    computed: {
      ...mapGetters([
        'treeCollection'
      ]),
      defaultMenu () {
        return this.defaultPage.replace(/\?.*/, '')
      },
      treeWidth () {
        return this.showMenu ? '200px' : '0'
      },
      currentTime () {
        let date = new Date()
        let day = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()]
        return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日 ' + day
      }
    },
    watch: {
      navMenus () {
        this.$nextTick(() => {
          this.$refs.menuTree.filter('')
        })
      }
    },
    methods: {
      ...mapActions([
        'updateTreeCollection'
      ]),
      handleUserCommand (command) {
        if (command === 'dialogFormVisible') {
          this.dialogFormVisible = true
        } else if (command === 'logout') {
          this.logOut()
        } else {
          console.error('no match user dropdown command')
        }
      },
      cancelPasswdUpdate () {
        this.dialogFormVisible = false
        this.$refs.passwordForm.resetFields()
      },
      updatePasswd () {
        this.$refs.passwordForm.validate((valid) => {
          if (valid) {
            var requestBody = {}
            requestBody.oldPassword = this.passwdFormData.oldPassword
            requestBody.newPassword = this.passwdFormData.newPassword
            indexApi.updatePasswd(requestBody)
              .then(re => {
                this.$message.success('密码重置成功!请重新登录')
                this.$router.push({ path: '/login' })
                this.dialogFormVisible = false
              })
          } else {
            return false
          }
        })
      },
      closeAll (tag, action) {
        // 由于element-ui未提供关闭全部tab的功能，所以使用了一种非常不推荐的hack方式
        if (action === 'add') {
          this.pages.splice(1, this.pages.length - 1)
          this.defaultPage = this.pages[0].name
        }
      },
      broadcastToIframe (value) {
        const iframes = this.pages.map((item, index) => {
          return this.$refs[`iframe${index}`] ? this.$refs[`iframe${index}`][0].contentWindow : null
        })
        iframes.forEach(iframe => {
          if (!iframe) return
          iframe.postMessage({
            type: 'BROADCAST',
            value: value
          }, '*')
        })
      },
      toggleMenu () {
        this.showMenu = !this.showMenu
      },
      filterMenu (v, data) {
        return !data.hidden
      },
      close (name) {
        let tabs = this.pages
        let activeName = this.defaultPage
        if (activeName === name) {
          tabs.forEach((tab, index) => {
            if (tab.name === name) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
          this.defaultPage = activeName
        }
        this.pages = tabs.filter(tab => tab.name !== name)
      },
      chooseTab (item) {
        if (item.index === '0') return
        let index = this.pages[parseInt(item.index)].id
        let currTree = []
        for (let i of this.treeCollection) {
          if (index === i.id) {
            currTree = i
          }
        }
        this.navMenus = currTree
        this.defaultNav = index
        this.$nextTick(() => {
          this.$refs.menuTree.setCurrentKey(item.name, true)
          const node = this.$refs.menuTree.store.currentNode
          node.expand(null, true)
        })
      },
      choosePage (value) {
        // const val = value.menuUrl + '?t=' + (new Date().getTime())
        // 解决左侧菜单无效的问题
        const val = value.menuUrl
        // const path = val ? val.replace(/\?.*/, '') : ''
        const result = recursion(this.navMenus.data, 'menuUrl', val, 'children')
        if (!result || !result.menuUrl || /_/.test(result.id)) return
        const page = {
          title: result.name,
          name: result.id,
          path: val,
          id: this.navMenus.id,
          nodeId: result.id,
          closable: true
        }
        const currentPage = this.pages.filter(item => item.name.replace(/\?.*/, '') === page.name.replace(/\?.*/, ''))[0]
        if (currentPage) {
          currentPage.name = page.name
          const currentFrame = document.getElementById(`iframe${currentPage.name}`)
          if (currentFrame) {
            try {
              currentFrame.contentWindow.location.reload()
            } catch (e) {
              console.log(e)
            }
          }
        } else {
          this.pages.push(page)
        }
        this.defaultPage = page.name
      },
      chooseNav (index) {
        this.defaultNav = index
        if (local === false) {
          let moduleId
          remoteApi.getMenusByModule({moduleId: moduleId})
            .then(data => {
              const res = data.data
              console.log(res)
              this.defaultNav = moduleId
              this.navMenus = {id: moduleId, data: res}
              // this.updateTreeCollection({id: moduleId, data: res})
              this.setNodeOpen(res)
              return Promise.resolve()
            })
        } else {
          indexApi.getMenusByModule({moduleId: index})
            .then(re => {
              const res = re
              this.navMenus = {id: index, data: res}
              this.expendNode = []
              this.setNodeOpen(res)
              for (let i of this.treeCollection) {
                if (index === i.id) return
              }
              // this.updateTreeCollection({id: index, data: res})
            })
        }
      },
      /**
       * getNavs 获取导航数据
       *
       */
      getNavs () {
        indexApi.getNavs()
          .then(data => {
            const navArr = data
            let max = 10
            if (document.body.clientWidth <= 1600 && document.body.clientWidth > 1366) {
              max = 8
            } else if (document.body.clientWidth <= 1366 && document.body.clientWidth >= 1152) {
              max = 5
            } else if (document.body.clientWidth < 1152) {
              max = 4
            }
            if (navArr.length > max) {
              navArr.splice(max + 1, 0, '#')
              let point = '#'
              let idx = navArr.indexOf(point)
              this.navs = navArr.slice(0, idx)
              const moreArr = navArr.slice(idx + 1)
              if (moreArr.length > 0) {
                this.navsMore = navArr.slice(idx + 1)
                this.moreVisable = ''
              }
            } else {
              this.navs = navArr
            }
            if (navArr.length > 0) {
              return navArr[0].moduleId + ''
            }
          }, e => {
            console.error(e)
          })
            .then(moduleId => {
              this.getMenus(moduleId)
            }).catch(e => {
              console.error(e)
            })
      },
      /**
       * getMenus 获取左侧menu数据 渲染
       *
       * @param  {String} moduleId 第一个模块的id标识
       */
      getMenus (moduleId) {
        if (!moduleId) return false
        if (local === false) {
          remoteApi.getMenusByModule({moduleId: moduleId})
            .then(data => {
              const res = data.data
              console.log(res)
              this.defaultNav = moduleId
              this.navMenus = {id: moduleId, data: res}
              // this.updateTreeCollection({id: moduleId, data: res})
              this.setNodeOpen(res)
              return Promise.resolve()
            })
        } else {
          indexApi.getMenusByModule({moduleId: moduleId})
            .then(data => {
              const res = data
              console.log(res)
              this.defaultNav = moduleId
              this.navMenus = {id: moduleId, data: res}
              // this.updateTreeCollection({id: moduleId, data: res})
              this.setNodeOpen(res)
              return Promise.resolve()
            })
        }
      },
      /**
       * 注销
       *
       */
      logOut () {
        indexApi.logOut()
          .then(data => {
            this.$router.push({ path: '/login' })
          })
      },
      /**
       * setNodeOpen 设置左侧展开标识
       *
       * @param  {Array} tree 左侧菜单树
       */
      setNodeOpen (tree) {
        for (var obj of tree) {
          if (obj.open) {
            this.expendNode.push(obj.id)
          }
          if (obj.children) {
            this.setNodeOpen(obj.children)
          }
        }
      },
      getUrlParam (key) {
        if (!key) return null
        var str = location.hash.slice(3)
        if (!str) return null
        var newArr
        var newObj = {}
        var i = 0
        var l
        newArr = str.split('&')
        l = newArr.length
        if (l === 1 && str.indexOf('=') < 0) return str
        for (; i < l; i += 1) {
          str = newArr[i].split('=')
          // 转换所有的整数内容为number对象
          newObj[str[0]] = str[1]
        }
        return newObj[key]
      },
      choosePageForMesBox (menuUrlM) {
        const val = menuUrlM
        // const path = val ? val.replace(/\?.*/, '') : ''
        // const result = recursion(this.navMenus.data, 'menuUrl', val, 'children')
        // if (!result || !result.menuUrl || /_/.test(result.id)) return
        const page = {
          title: '我的消息箱',
          name: '100',
          path: val,
          id: this.navMenus.id,
          nodeId: '100',
          closable: true
        }
        const currentPage = this.pages.filter(item => item.name.replace(/\?.*/, '') === page.name.replace(/\?.*/, ''))[0]
        if (currentPage) {
          currentPage.name = page.name
          const currentFrame = document.getElementById(`iframe${currentPage.name}`)
          if (currentFrame) {
            try {
              currentFrame.contentWindow.location.reload()
            } catch (e) {
              console.log(e)
            }
          }
        } else {
          this.pages.push(page)
        }
        this.defaultPage = page.name
      }
    },
    mounted () {
      /**
       * 注册addEventListener
       */
      handler = receiveMsg.bind(this)
      window.addEventListener('message', handler, false)
      const errorMsg = decodeURI(this.getUrlParam('errorMsg'))
      if (errorMsg && errorMsg !== 'null') {
        this.$message.error(errorMsg)
      }
      const welcomeUrl = window.location.protocol + '//' + window.location.host + '/#/welcome'
      this.currUserName = cookies.getCookie('currUserName')
      this.currEnv = getCurrEnvContext()
      this.getNavs()
      this.pages.push({
        title: '首页',
        name: '0',
        path: welcomeUrl,
        id: '0'
      })
    },
    destroyed () {
      if (!handler) return
      window.removeEventListener('meesage', handler)
      handler = null
      clearInterval(this.timer)
      clearInterval(this.timer2)
    }
  }
</script>
